<?php
class School_ extends MY_Controller {
	
	private $mainMenuItems;
	
	/**
	 * array with the name of all content views used in this controler
	 */
	var $views = array(
		'schoolBodyMain'			=>'school/content/schoolBodyMain',
		'schoolBodyOffers'			=>'school/content/schoolBodyOffers',
		'schoolBodyExtras'			=>'school/content/schoolBodyExtras',
		'schoolBodySchedules'		=>'school/content/schoolBodySchedules',
		'schoolBodyReservations'	=>'school/content/schoolBodyReservations',
		'schoolBodyClasses'			=>'school/content/schoolBodyClasses',
		'schoolBodySettings'		=>'school/content/schoolBodySettings',
		'schoolBodyProfile'			=>'school/content/schoolBodyProfile',
		'schoolBodyMakeReservation'	=>'school/content/schoolBodyMakeReservation',
		'schoolBodyHotel'			=>'school/content/schoolBodyHotel',
		'schoolBodyTemplate'		=>'school/content/schoolBodyTemplate'
	);
	
	
	
	
	
	
	
	/**
	 * Constructor ... here is checked if the user is logged in
	 */
	function School() {
		parent::__construct();
		
		// check if a School user is logged in ...
		if ($this->ion_auth->is_group("school")) { 
			
			$this->load->helpers(array('html'));
			
			$this->load->library(array('carabiner','template','fuelmenu','ion_auth','mylibrary'));
			
			$this->load->model('School_model');
			
			$this->lang->load('school');
			
			
			$this->carabiner->css('reset.css');
			//$this->carabiner->css('../templates/magicAdmin/css/reset.css');
			//$this->carabiner->css('../templates/magicAdmin/css/styles.css');
			$this->carabiner->css('../templates/magicAdmin/css/grid.css');
			$this->carabiner->css('../templates/magicAdmin/css/theme-red.css');
			//$this->carabiner->css('reset.css');
			$this->carabiner->css('school.css');
			//$this->carabiner->css('school/grid.css');
			//$this->carabiner->css('school/theme-blue.css');
			
			$this->_configTemplate();	
			$this->_createMainMenuItems();
			$this->_setData();
		}
		else {		// not a school user? redirect ...
			redirect('Login/index');
		}
	}
	
	
	
	
	
	
	
	
	/**
	 * Config the template library
	 */
	private function _configTemplate() {
		$this->template->title('Radical Booking - Escola');
		$this->template->enable_parser(false);
		$this->template->set_layout('schoolLayout');
	}
	
	
	/**
	 * set global var's to be forward to all views
	 */
	private function _setData() {
		
		$school = $this->School_model->getUserInfo($this->ion_auth->get_user()->id);
		
		$user = $school;
		
		// format fields with data
		$school->created_on = date('Y-m-d H:i:s',$school->created_on); 
		$school->last_login = date('Y-m-d H:i:s',$school->last_login); 
		
		$this->template->set('school',$school);
		$this->template->set('user',$user);
	}
	
	
	/**
	 * Create the for the main Navigation Menu 
	 */
	private function _createMainMenuItems() {
			
		// create the entries
		$this->mainMenuItems =
		array (
				'School/index'				=>	$this->lang->line('school.menu.main'),
				'Sch/SchOffers'				=>	$this->lang->line('school.menu.lnk1'),
				'School/extras'				=>	'Extras',
				'School/schedules'			=>	$this->lang->line('school.menu.lnk2'),
				//'School/makeReservation'	=>	'Reservar',
				'Sch/SchMakeResevation'		=>	'Reservar',
				'School/reservations'		=>	$this->lang->line('school.menu.lnk3'),
				'School/classes'			=>	'Aulas',
				'Sch/SchTemplate'			=>	'Template'
				//'School/settings'			=>	'settings'
		);
	}
	
	
	/**
	 * function to get the menu to be drawn
	 */
	private function _navigationMenu() {
		
		// set this link as the active one
		$active = $this->uri->rsegment(1).$this->uri->slash_rsegment(2,'leading');
		
		$param = array(
			'active_class'			=>'actual',
			'use_titles'			=>false,
			'container_tag_id'		=>'nav',
		);
		$this->fuelmenu->initialize($param);
		
		return $this->fuelmenu->render($this->mainMenuItems,$active,NULL,'basic');
	}
	
	
	
	
	
	
	
	
	
	
	/**
	 * Main entry point
	 */
	public function index() {
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','bootstrap'));
		else
			$this->template->set('groupLibraries',array('jquery_local','bootstrap_local'));
		
		// send hotel information to the view
		$this->template->set('hotels', $this->School_model->getHotelsInfo());
		
		$this->template->set('menu',$this->_navigationMenu());
		
		$this->template->build($this->views['schoolBodyMain']);
	}
	
	/**
	 * Show, edit and create OFFERS
	 */
	public function offers() {
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','jtable','validationEngine'));
		else 
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','jtable','validationEngine'));
		
		// local assets
		$this->carabiner->js('school/schoolOffers.js');
		
		// render the menu
		$this->template->set('menu',$this->_navigationMenu());
		
		// load view
		$this->template->build($this->views['schoolBodyOffers']);
	}
	
	
	public function extras() {
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','jtable','validationEngine'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','jtable','validationEngine'));
		
		// local assets
		$this->carabiner->js('school/schoolExtras.js');
		
		// render the menu
		$this->template->set('menu',$this->_navigationMenu());
		
		// load view
		$this->template->build($this->views['schoolBodyExtras']);
	}
	
	/**
	 * SCHEDULES - show's calendar
	 */
	public function schedules() {
		
		// JS includes ...
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','fullcalendar'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','fullcalendar',));
		
		// load local assets
		$this->carabiner->js('school/schoolSchedules.js');
		$this->carabiner->css('school/schedules.css');
		
		// render the menu
		$this->template->set('menu',$this->_navigationMenu());
		
		// load view
		$this->template->build($this->views['schoolBodySchedules']);
	}
	
	/**
	 * RESERVATIONS - show the list of reservations
	 */
	public function reservations() {
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','datatables','bootstrap'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','datatables_local','bootstrap_local'));
		
		$this->carabiner->css('school/reservation.css');
		$this->carabiner->js('school/schoolReservation.js');
		
		// render the menu
		$this->template->set('menu',$this->_navigationMenu());
		
		// load view
		$this->template->build($this->views['schoolBodyReservations']);
	}
	
	/**
	 * CLASSES - list of classes
	 */
	public function classes() {
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','datatables','jqueryUI_bootstrap'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','datatables_local','jqueryUI_bootstrap'));
		
		$this->carabiner->css('school/classes.css');
		$this->carabiner->js('school/schoolClasses.js');
		
		// tmp code. ... 
		$now = date('Y-m-d H:i:s',time());
		$result = $this->db->select('*')->from('schedule')->where('start >', $now)->get()->result();
		//$this->chromephp->log('schedule: ', $result);
		
		//$this->firephp->log($this->_navigationMenu());
		
		$this->template->set('menu',$this->_navigationMenu());
		
		$this->template->build($this->views['schoolBodyClasses']);
	}
	
	public function template() {
		
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery'));
		else
			$this->template->set('groupLibraries',array('jquery_local','','',''));
		
		$this->template->set('menu',$this->_navigationMenu());
		
		$this->template->build($this->views['schoolBodyTemplate']);
	}
	
	
	public function settings() {
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui',''));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local',''));
		
		$this->template->set('menu',$this->_navigationMenu());
		
		$this->template->build($this->views['schoolBodySettings']);
	}
	
	public function profile() {
	
		// witch libraries we need in this view? only those will be loaded in the head view file
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryForm','bootstrap'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryForm_local','bootstrap_local'));
		
		$this->carabiner->js('school/schoolProfile.js');
		
		// render the menu
		$this->template->set('menu',$this->_navigationMenu());
		
		// load view
		$this->template->build($this->views['schoolBodyProfile']);
	}

	/**
	 * View reservation data, and set reservation here
	 */
	public function makeReservation() {
		
		// JS includes ...
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','bootstrap','datatables'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','bootstrap_local','datatables_local'));
		
		//$this->carabiner->css('school/makeReservation.css');
		$this->carabiner->js('school/schoolMakeReservation.js');
		
		$this->template->set('menu',$this->_navigationMenu());
		
		$this->template->set('classes',$this->School_model->getAvailableClasses());
		
		$this->template->build($this->views['schoolBodyMakeReservation']);
	}
	
	/**
	 * show and edit hotel information
	 * @param $hotelId hotel identification
	 */
	public function hotel( $hotelId = null ) {
		
		if (empty($hotelId))
			redirect('School');
		
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','jqueryForm','bootstrap'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','jqueryForm_local','bootstrap_local'));
		
		//$this->carabiner->js('school/schoolMakeReservation.js');
		
		// set information about the given hotel
		$hotel = $this->School_model->getHotelsInfo($hotelId);
		$this->template->set('hotel', $hotel);
		//$hotel->payment = 100;
		//$this->chromephp->log('hotel: ',$hotel);
		
		$this->carabiner->js('school/schoolHotel.js');
		
		$this->template->set('menu',$this->_navigationMenu());
		
		$this->template->build($this->views['schoolBodyHotel']);
	}
	
	
	
	/**
	* Logout the School user from the system
	*/
	public function logout() {
		$this->ion_auth->logout();
		redirect('Main/index');
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	* Create an offer 
	* Function called from jtable schoolOffers.js
	*/
	public function jtableCreateOffer() {
		
		$emptyRecord 	= '{ "Result":"OK", 	"Record":{}}';
		$singleRecord 	= '{ "Result":"OK",		"Record":{"id":"18","users_id":"3","name":"","price":"0.00","numberOfClasses":"0","level":"beginner","minPart":"0","maxPart":"0","active":"1","remainingClasses":"0","part":"0","description":"","bgColor":null,"borderColor":null,"textColor":null,"color":null}}';
		$genericError 	= '{ "Result":"ERROR", 	"Message":"generic Error" }';
	
		// check if all POST fields are ok ... implement this later
		
		// *** tmp ***
		//$this->chromephp->log('POST: ', $_POST);
		//echo $noRecord;
		//echo $genericError;
		//echo $singleRecord;
		//return;
		// *** *** ***
	
		// create offer and print the newly created offer in json format
		if (isset($_POST['name']))
			echo $this->School_model->addOffer($_POST);
		else {
			show_404('',false);
		}
	}
	
	
	
	/**
	 * Send an json object to the jtable with all
	 * offers from the current logged in school user
	 */
	public function jtableReadOffer() {
		
		$emptyRecord = ' { "Result":"OK", "Records":[] }'; 
		
		$sampleRecords = '
			{
				"Result":"OK",
				"Records":
				[
					{
						"id":"1",
						"key1":"val1",
						"key2":"val2"
					},
					{
						"id":"2",
						"key1":"val1",
						"key2":"val2"
					}
				],
				"TotalRecordCount":2
			}
		';
		
		$offers = $this->School_model->getOffer(array('visible'=>'yes'));
		
		if ($offers) {
			
			$arr = array("Result"=>"OK","Records"=>$offers,"TotalRecordCount"=>count($offers));
			echo json_encode($arr);
		}
		else
			echo $emptyRecord;
	}

		
	/**
	 * update offer
	 */
	public function jtableUpdateOffer() {
		
		$errorMsg = '{ "Result":"ERROR", "Message":"Error trying to update offer" }'; 
		
		// check if all POST fields are ok ... implement later
		
		// if all fields are ok ... update offer
		if (isset($_POST['id'])) {
			
			// workarround ... jtable dont send active value when its set to 0 ...
			if (!isset($_POST['active'])) { 
				$_POST['active'] = 0;
			}
			//$this->firephp->log($_POST);
			$this->School_model->updateOffer($_POST);
			echo '{"Result":"OK"}'; 
		}
		else {
			echo $errorMsg;
		}
	}
	
	/**
	 * Delete the offer with id = $_POST['id'] 
	 * A json object with an "ok" or "error" status is printed
	 */
	public function jtableDeleteOffer() {
		
		$okMsg 		= '{"Result":"OK"}';
		$errorMsg 	= '{ "Result":"ERROR", "Message":"Error trying to delete offer" }'; 
		$errTmp 	= '{ "Result":"ERROR", "Message":"tmp error" }'; 
		
		$offerId = null;
		
		// Check offer ID ...
		if (isset($_POST['id'])) {
			$offerId = $_POST['id'];
		}
		else {
			echo $errorMsg;
			return;
		}
		
		// $this->School_model->deleteOffer($_POST['id']);
		//$visible = $this->db->select('visible')->from('offer')->where('id',$offerId)->get()->row()->visible;
		//$this->chromephp->log($visible);
		
		if (!$visible) {
			$this->chromephp->log('visible');
		}
		else {
			
		}
		
		//$this->db->where('id',$offerId)->delete('offer');
		
		//echo $okMsg;
		echo $errTmp;
	}
	
	
	
	
	
	public function jtableCreateExtra()	{
		
		$errorMsg = '{ "Result":"ERROR", "Message":"Error while trying to create the extra" }';
		
		//$emptyResult = '{ "Result":"OK", "Records":[]}'; 
		
		// check if post has all fields ok
		
		$result = $this->School_model->createExtra($_POST);
		
		if ($result) {
			echo $result;	
		}
		else {
			echo $errorMsg;
		}
	}
	
	/**
	 * Fill the table with extras
	 */
	public function jtableReadExtra() {
		
		$noRecords = '{"Result":"OK", "Records":[]}';
		
		$offerId = $this->input->get('offerId');
		
		if ($offerId == null)
			$records = $this->School_model->readExtra(); 
		else 
			$records = $this->School_model->readExtra(null,$offerId); 
		
		if ($records)
			echo $records;
		else 
			echo $noRecords;
	}	
	
	
	
	public function jtableUpdateExtra() {
		
		// msg to inform
		$okMsg 		= '{"Result":"OK"}';
		$errorMsg 	= '{ "Result":"ERROR", "Message":"Error while trying to update the extra" }';
		
		// workarround ... jtable dont send active value when its set to 0 ...
		if (!isset($_POST['active'])) { 
			$_POST['active'] = 0;
		}
		
		if (!isset($_POST['included_in_offer']))
			$_POST['included_in_offer'] = 0;
		
		// update data
		$res = $this->School_model->updateExtra($_POST);
		
		if ($res)
			echo $okMsg;
		else
			echo $errorMsg;
	}
	
	
	public function jtableDeleteExtra() {
		
		$okMsg 		= '{ "Result":"OK"}';
		$errorMsg 	= '{ "Result":"ERROR", "Message":"Erro ao tentar eliminar o extra" }';
		
		$extraId = $_POST['id'];
		
		// validate fields
		
		if ( $this->School_model->deleteExtra($extraId) )
			echo $okMsg;
		else
			echo $errorMsg;
		
		return;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * Called from file 'schedules.js' inside the view 'schoolBodySchedules' to create and store a schedule.
	 * This function is called from schedules.js anytime an event is created in the fullcalendar 
	 * @return JSON $data string in JSON format with data to draw the event in the calendar. False if no event is created
	 */
	function fullCalCreateSchedule() {
		
		// check if all POST fields are ok
		
		// convert from 'timestamp' to 'datetime'
		$eventStart 		= date('Y-m-d H:i:s',$_POST['eventStart']);
		$eventEnd			= date('Y-m-d H:i:s',$_POST['eventEnd']);
		
		$offerId = $_POST['offerId'];
		
		$offer = $this->School_model->getOffer(array('offerId'=>$offerId));

		$numberOfClasses = $offer->numberOfClasses;
		$lastClassSch = $this->School_model->getLastClassScheduled($offerId);
		$qtLastClassSch = $this->School_model->getLastScheduleQuantity($lastClassSch);

		$scheduleId = false;

		/*
		$this->firephp->log($lastClassSch,'lastClassSch');
		$this->firephp->log($qtLastClassSch,'qtLastClassSch');
		$this->firephp->log($numberOfClasses,'numberOfClasses');
		$this->firephp->log($offer,'offer');
		*/

		// ... nothing scheduled yet for this offer ... create new class  
		if ( $lastClassSch == null or $qtLastClassSch == $numberOfClasses ) { 

			$classId = $this->School_model->addClass($offer);

			if ($classId == null) {

				$scheduleId = false;
			}
			else { // ... create schedule

				$options = array(
					'class_id' 	=> $classId, 
					'offer_id'  => $offer->id,
					'start'		=> $eventStart,
					'end'		=> $eventEnd
				);

				$scheduleId = $this->School_model->addSchedule($options, array('editable' => 1));
			}
		}

		// ... it can be create more schedules for the last class
		if ( $qtLastClassSch != $numberOfClasses and $qtLastClassSch != null and $numberOfClasses != null ) {

			$options = array(
				'class_id' 	=> $lastClassSch, 
				'offer_id'  => $offer->id,
				'start'		=> $eventStart,
				'end'		=> $eventEnd
			);

			$scheduleId = $this->School_model->addSchedule($options, array('editable' => 1));
		}

		$eventData['id']			= $scheduleId;
		$eventData['title']			= $_POST['offerName'];

		echo json_encode($eventData);
	}
	
	
	/**
	* Function that returns fullCalendar events from the
	* database table 'schedules'
	* This function is called everytime fullcalendar renders one of the views
	* @todo review this fucking mess
	*/
	public function fullCalReadSchedule() {
		
		// convert from unix timestamp to datetime ... 
		$start 	= date('Y-m-d H:i:s',$_GET['start']);
		$end	= date('Y-m-d H:i:s',$_GET['end']);

		$this->School_model->flushPastEvents($start, $end);
		$this->School_model->flushOffers();
		$this->School_model->flushClientReserves();
	
		$results = $this->School_model->getSchedule(array('start'=>$start,'end'=>$end,'incompleteClasses'=>true)); 
		
		if ( $results ) {
			// fix JSON
			foreach ($results as $key=>$value) {
				$results[$key]['editable']	= $results[$key]['editable'] 	== 0 ? false:true;
				$results[$key]['allDay']	= $results[$key]['allDay'] 		== 0 ? false:true;
			}
			echo json_encode($results);
		}
		else {
			echo false;
		}
	}
	
	/**
	 * Function to fill the dropbox options with all available offers
	 * when an calendar event is drawn
	 */
	public function fullCalAvailableOffers() {
		
		//$offers =  $this->School_model->getOffer(array('active'=>'yes','available'=>'true'));
		//$this->firephp->log($offers,'offers');
		$offers = $this->School_model->getOffers2Schedule();
		//$this->firephp->log($tmp);
		echo json_encode($offers);
	}
	
	
	/**
	 * called from 'schedules.js' when an schedule event is clicked in fullcalendar.
	 * This function returns a list of clients with reservation in the offer associated to the given schedule
	 */
	public function fullCalGetClientInSchedule() {
	
		//$tmp = '[{"clientId":"#","clientName":"...","clientEmail":"...","clientPhone":"...","date":"...","hotel":"...","freeSpots":20}]';
		//$lugares = '[{"freeSpots":20}]';
	
		$schedule_id = $_POST['scheduleId'];
	
		$selectFields = '
		client.id 					as clientId,
		client.name					as clientName,
		client.email				as clientEmail,
		client.phone				as clientPhone,
		reserve.date		as date,
		meta.company				as hotel
		';
	
		$schedule = $this->db->select('class_id,offer_id')->from('schedule')->where('id',$schedule_id)->get()->row();
		$class_id = $schedule->class_id;
		$offer_id = $schedule->offer_id;
	
		// ... if no class already created for this schedule ...
		if (!$class_id) {
			// get the max participants number of this offer
			$freeSpots = array(
					array('freeSpots'=>$this->db->select('maxPart')->from('offer')->where('id',$offer_id)->get()->row()->maxPart)
			);
			echo json_encode($freeSpots);
			return;
		}
	
		$this->db->select($selectFields);
		$this->db->from('reserve');
		$this->db->join('client', 'client.id = reserve.client_id','inner');
		$this->db->join('users', 'users.id = client.users_id','inner');
		$this->db->join('meta', 'meta.user_id = users.id','inner');
		$this->db->where('class_id',$class_id);
		$result = $this->db->get()->result_array();
	
		$class = $this->db->select('maxPart, part')->from('class')->where('id', $class_id)->get()->row();
	
		$result[0]['freeSpots'] = $class->maxPart - $class->part;
		$this->chromephp->log($class);
	
		echo json_encode($result);
		return;
	}
	
	
	
	
	
	/**
	 * Called when 'reservation' button is pressed in the file 'makeReservation.js'
	 */
	public function createReservationAction() {
		
		$ok 					= '{"Result":"OK","msg":"Reserva efectuada com sucesso"}';
		$okTestMsg				= '{"Result":"OK","msg":"mensagem de test"}';
		$errGeneric 			= '{"Result":"ERROR","msg":"Não foi possivel fazer a reserva"}';
		$errTest 				= '{"Result":"ERROR","msg":"teste"}';
		$errClient 				= '{"Result":"ERROR","msg":"Cliente ja esta registado para esta oferta"}';
		$errFull 				= '{"Result":"ERROR","msg":"Não existem vagas disponiveis"}';
		$errClassFull 			= '{"Result":"ERROR","msg":"Não existem vagas para esta aula"}';
		$errOfferNotAvailable 	= '{"Result":"ERROR","msg":"Esta oferta não está disponivel"}';
		
		//$this->chromephp->log('POST',$_POST);
		
		$offer_id 	= $_POST['offer_id'];
		$class_id 	= $_POST['class_id'];
		$client_id 	= $_POST['client_id'];
		
		if (isset($_POST['extras']))
			$extrasIDs 	= $_POST['extras'];
		else
			$extrasIDs = null;
		
		//echo $errTest;
		//return;
		
		if ($this->School_model->isClassFull($class_id)) {
			echo $errClassFull;
			return;
		}
		
		if ($this->School_model->isClienteInReservationList($client_id, $class_id)) {
			echo $errClient;
			return;
		}
		else { // ... make the reservation
			
			$succ = $this->School_model->createReservation($client_id,$class_id,$extrasIDs);
			
			if (!$succ) {
				echo $errGeneric;
				return;
			}
		}
		
		// send mail
		
		echo $ok;
		return;
	}
	
	
	/**
	 * function to fill the js plugin datatable with reservations.
	 * Called from view 'schoolBodyReservation' to show a list with all reservations maded so far maded so far 
	 */
	public function readReservationAction() {
		
		$noData 	= '{"data":[]}';
		
		//$this->chromephp->log('POST: ',$_POST);
		
		$offerId 	= $_POST['offerId'];
		$start		= $_POST['start'];
		$end		= $_POST['end'];
		
		// javascript null val is passed as a string
		if ( $start == 'null' ) $start = NULL;
		if ( $end == 'null' ) 	$start = NULL;
		
		$school_id = $this->ion_auth->get_user()->id;
		
		$now = date('Y-m-d H:i:s',time());
		
		// will hold class IDs with schedules between a date range
		$classesInRange = array();
		
		// only enter here if a date range is specified
		if ( $start != null && $end != null ) {
			
			$classesInRange = $this->School_model->getClassesWithSchedulesInRange($start, $end);
			
			// if no schedules in the range, no data should be returned
			if (empty($classesInRange)) {
				echo $noData;
				return;
			}
		}
		
		// only show reservations maded by this school or hotels associated to this school
		$userIDs = $this->School_model->getHotels();
		array_push($userIDs, $school_id);
		
		$selectFields = '
			client.id				as clientID,
			class.id  				as classID,
			users.id  				as userID,
			reserve.id		as clientReservesID,
			offer.name 				as offerName,
			client.name 			as clientName,
			client.email 			as clientEmail,
			client.phone 			as clientPhone,
			reserve.date	as clientReserveDate,
			meta.company
		';
		
		$this->db->select($selectFields);
		$this->db->from('reserve');
		$this->db->join('class','class.id = reserve.class_id','inner');
		$this->db->join('offer','offer.id = class.offer_id','inner');
		$this->db->join('client','client.id = reserve.client_id','inner');
		$this->db->join('users','users.id = client.users_id','inner');
		$this->db->join('meta','meta.user_id = users.id','inner');
		
		$this->db->where_in('users.id', $userIDs);
		$this->db->where('offer.users_id', $school_id);
		
		if( $offerId )
			$this->db->where('offer.id', $offerId);
		
		if ( $start != NULL && $end != NULL ) {
			$this->db->where_in('class.id', $classesInRange);
		}
		
		$result = $this->db->get()->result();
		
		$dataTableResult['data'] = $result;
		echo json_encode($dataTableResult);
		return;
	}
	
	
	public function updateReservationAction() {
		
	}
	
	public function deleteReservationAction() {
		
	}
	
	/**
	 * feed the datatable from class section with a list of upcomming classes
	 */
	public function readClassesAction() {
		
		$noData 	= '{"data":[]}';
		$oneRecord 	= '{"data":[{"offerName":"Nome da oferta","classes":"2","start":"inicio","part":"3","spots":"4","company":"escola 1"}]}';
		$this->chromephp->log($_POST);
		
		$user_id = $this->ion_auth->get_user()->id;
		
		$now = date('Y-m-d H:i:s',time());
		
		$this->db->select('class_id, offer_id, numberOfClasses, count(*) as quantity')->from('schedule');	
		$this->db->where('start >', $now);
		$this->db->join('offer', 'offer.id = schedule.offer_id', 'inner');
		$this->db->join('users', 'users.id = offer.users_id', 'inner');
		$this->db->where('users.id', $user_id);
		$this->db->group_by('class_id');
		$result = $this->db->get()->result();
		
		$futureClasses = array();
		
		foreach ( $result as $value ) {
			if ( $value->numberOfClasses == $value->quantity )
				array_push($futureClasses, $value->class_id);
		}
		
		$add2query = implode(',', $futureClasses);
		
		$query = $this->db->query('
			select 
		    	futureClasses.id        as classId, 
			    futureClasses.offer_id  as offerId, 
			    schedule.id             as scheduleId, 
			    offer.name              as offerName, 
			    offer.numberOfClasses   as classes, 
			    futureClasses.part      as part, 
			    futureClasses.maxPart   as spots,
	    		start
			from (select * from class where id in ('.$add2query.')) as futureClasses
			inner join schedule on schedule.class_id = futureClasses.id
			inner join offer on offer.id = futureClasses.offer_id 
			inner join users on users.id = offer.users_id group by futureClasses.id;
		');
		
		$result = $query->result();
		
		$dataTableResult['data'] = $result;
		echo json_encode($dataTableResult);
		return;
	}
	
	/**
	 * function called from 'makeReservation.js' to create a new client
	 */
	public function createClientAction() {
		
		// define message to return here
		$okMsg		= '{"Result":true,"msg":"Cliente criado"}';
		$errMsg		= '{"Result":false,"msg":"default error"}';
		$err01		= '{"Result":false,"msg":"existem campos em branco"}';
		
		$cientId = $_POST['clientId'];
		
		//echo $okMsg;
		//return;
		
		// data to be inserted the the table 'client'
		$client = array();
		$client['name'] 		= $_POST['name'];
		$client['address'] 		= $_POST['address'];
		$client['email'] 		= $_POST['email'];
		$client['phone'] 		= $_POST['phone'];
		$client['birthday'] 	= $_POST['birthday'];
		$client['sex'] 			= $_POST['sex'];
		$client['height'] 		= $_POST['height'];
		$client['weight'] 		= $_POST['weight'];
		$client['nationality'] 	= $_POST['nationality'];
		$client['info'] 		= $_POST['info'];
		
		//$this->firephp->log($client);
		
		/*
		// check if all fields are filled
		foreach ($client as $val) {
			if (empty($val)) {
				echo $err01;
				return;
			}
		}
		*/
		// validate data with the function 'filter_var' ... 
		
		$users_id = $this->ion_auth->get_user()->id;
		
		$this->db->set('users_id',$users_id);
		
		$succ = $this->db->insert('client',$client);
		
		if ($succ) {
			echo $okMsg;
			return;
		}
		else {
			echo $errMsg;
			return;
		}
	}
	
	public function readClientAction() {
		
		
	}
	
	public function updateClientAction() {
		
		// define message to return here
		$okMsg		= '{"Result":true,"msg":"Cliente criado"}';
		$okMsgUpt	= '{"Result":true,"msg":"Cliente actualizado"}';
		$errMsg		= '{"Result":false,"msg":"default error"}';
		$errMsgUpt	= '{"Result":false,"msg":"Não foi possivel actualizar o cliente"}';
		$err01		= '{"Result":false,"msg":"existem campos em branco"}';
		$errGeneric	= '{"Result":false,"msg":"generic error"}';
		
		$clientId = $_POST['clientId'];
		
		if (!$clientId) {
			echo $errGeneric;
			return;
		}
		
		// validate client data here
		
		// update languages
		
		$this->firephp->log($_POST,'_POST');
		
		$data = array(
			'name' 			=>$_POST['name'],
			'address' 		=>$_POST['address'],
			'email'			=>$_POST['email'],
			'phone' 		=>$_POST['phone'],
			'birthday' 		=>$_POST['birthday'],
			'sex'			=>$_POST['sex'],
			'height'		=>$_POST['height'],
			'weight'		=>$_POST['weight'],
			'nationality'	=>$_POST['nationality'],
			'info'			=>$_POST['info']
		);
		
		$this->db->where('id',$clientId);
		$upt = $this->db->update('client',$data);
		
		if ($upt) {
			echo $okMsgUpt;
			return;
		}
		else {
			echo $errMsgUpt;
			return;
		}
	}
	
	public function deleteClientAction() {
		
	}
	
	
	/**
	 * retrieve all possible information about a given class
	 */
	public function getClassInfo() {
		
		$this->chromephp->log('POST: ', $_POST);
		
		$classID = $_POST['data']['classID'];
		
		$schedules = $this->School_model->getSchedule(array('class_id'=>$classID));
		
		$clients = $this->School_model->getClientsInClass($classID);
		
		foreach ($clients as $client) {
			$this->chromephp->log('clientId: ', $client->clientId);
		}
		
		$this->db->select('*')->from('reserve');
		$this->db->where('client_id',27);
		$this->db->where('class_id',$classID);
		$result = $this->db->get()->result();
		//$this->chromephp->log('result: ', $result);
		
		echo json_encode(array('schedules'=>$schedules,'clients'=>$clients));
		
		return;
	}
	
	
	/**
	 * get all clients to feed the datatable plugin
	 */
	public function getClients() {
		$clients = $this->School_model->getClient();
		$dataTableResult['data'] = $clients;
		echo json_encode($dataTableResult);
	}
	
	
	
	
	/**
	 * retrieve all available offers
	 * used to fill dropdown list in the view 'schoolBodyReservation'
	 */
	public function allOffers() {
		//$options = array('active'=>'yes','datatype'=>'json');
		//echo $this->School_model->getOffer($options);
		$offers = $this->School_model->getOffer(array('active'=>'yes'));
		echo json_encode($offers);
	}
	
	/**
	 * Function that retrieve a json file with
	 * all extras available to be included in the given offer.
	 * This function is called from 'offers.js' when the user choose the option to include extras
	 * $_GET['offerId']
	 * $_GET['userId']
	 */
	public function availableExtras() {
		
		$offerId = $_GET['offerId'];
		
		$users_id = $this->ion_auth->get_user()->id;
		//$userId = $_GET['userId'];
		//$offerId = 6;
		//$userId = 7;
	
		// get all extra's associated to the given offer
		$this->db->select('extra_id');
		$this->db->from('extra_offer');
		$this->db->where('offer_id',$offerId);
		$offerExtra = $this->db->get()->result();
		foreach ($offerExtra as $key => $value) {
			$offerExtra[$key] = $value->extra_id;
		}
	
		$this->db->flush_cache();
	
		$this->db->select('*');
		$this->db->from('extra');
		$this->db->where('included_in_offer',1);
		$this->db->where('users_id',$users_id);
		
		// dont show extras that are already part of this offer 
		if ($offerExtra)
			$this->db->where_not_in('id',$offerExtra);
		
		$result = $this->db->get()->result();
		
		echo json_encode($result);
	}
	
	/**
	 * Retrieves available extras to be included in the offer
	 */
	public function  getExtras2Include() {
		
		$users_id = $this->ion_auth->get_user()->id;
		
		//$offer_id = $_POST['offerId'];
		$offer_id = $_POST['data']['offer_id'];
		
	
		$options = array(
			'users_id'=>$users_id,
			'offer_id'=>$offer_id
		);
		
		$extras = $this->School_model->getExtra($options);
		
		//$this->firephp->log($extras);
		
		echo json_encode($extras);
	
		return;
	}
	
	
	/**
	 * Called from 'schoolOffers.js' to add free extras to a specific offer
	 */
	public function add_extra_offer() {
		
		$okMsg 		= '{"Result":"OK"}';
		$errorMsg 	= '{"Result":"ERROR", "Message":"Nao foi possivel associar o extra à oferta" }';
		
		$offerId = $_GET['offerId'];
		$extraId = $_GET['extraId'];
		
		$this->db->set('extra_id',$extraId);
		$this->db->set('offer_id',$offerId);
		
		$inserted = $this->db->insert('extra_offer');
		
		if ($inserted)
			echo $okMsg;
		else
			echo $errorMsg;
		
		return;
	}
	
	/**
	 * Called from 'schoolOffers.js' to remove free extras to a specific offer
	 */
	public function remove_extra_offer() {	
		
		$okMsg 		= '{"Result":"OK", "Message":"O extra foi removido" }';
		$errorMsg 	= '{"Result":"ERROR", "Message":"Nao foi possivel remover o extra da oferta" }';
		
		$this->chromephp->log('GET: ', $_GET);
		
		$offerId = $_GET['offerId'];
		$extraId = $_GET['extraId'];
		
		$this->db->where('offer_id', $offerId);
		$this->db->where('extra_id', $extraId);
		
		if ( $this->db->delete('extra_offer') )
			echo $okMsg;
		else 
			echo $errorMsg;
		
		return;
	}
	
	
	
	/**
	 * static events only for test 
	 */
	function staticEvents() {
		$year = date('Y');
		$month = date('m');
	
		$var1=json_encode(array(
	
		array(
								'id' 	=> 	111,
								'title' => 	"fixed array server 1",
								'start' => 	"$year-$month-26T10:30:00Z",
								'end' 	=> 	"$year-$month-26T11:30:00Z"
		//'url' => "http://yahoo.com/"
		)
	
		// 		array(
		// 							'id' 	=> 222,
		// 							'title' => "Event2",
		// 							'start' => "$year-$month-20",
		// 							'end' 	=> "$year-$month-22"
		// 							//'url' => "http://yahoo.com/"
		// 		)
	
	
	
	
		));
	
		$stringEvent = '
					[
						{
							"id":		111,
							"title":	"curso inicia��o em grupo",
							"start":	"2011-12-28 10:00:00",
							"end":		"2011-12-28 11:00:00",
							"color":	"fdasfdas",
							"editable":	0,
							"allDay":	false
						}
					]';
	
		$stringTmp = '
				{
					"id":				"1",
					"title":			"Curso Inicia\u00e7\u00e3o em grupo",
					"start":			"2012-12-27 13:00:00",
					"end":				"2012-12-27 14:00:00",
					"editable":			"1",
					"color":			"blue",
					"backgroundColor":	"",
					"borderColor":		"",
					"textColor":		""
				},
				{	"id":				"2","title":"Aula Inicia\u00e7\u00e3o em grupo","start":"2012-12-28 14:00:00","end":"2012-12-28 15:00:00","editable":"1","color":"blue","backgroundColor":"","borderColor":"","textColor":""}
			
			
			';
	
	
		$var2 = json_encode(array(
		array(
					'id'=>			1,
					'title' 	=> 	"test",
					'start' 	=> 	"2011-12-25 13:00:00",
					'end' 		=> 	"2011-12-25 18:00:00",
					'color'		=>	"green",
					'editable'	=>	false,
					'allDay'	=> 	false,
		)
		));
	
		$eventArr = array(
			array(
				'id'=>			111, // be carefull with id's
				'title' 	=> 	"test",
				'start' 	=> 	"2012-02-16 12:00:00",
				'end' 		=> 	"2011-02-16 13:00:00",
				'color'		=>	null,
				
				'editable'	=>	'1',
				'allDay'	=> 	'0',
			)
		);
		$eventArr[0]['editable'] = true;
		$eventArr[0]['allDay'] = true;
		$this->firephp->log($eventArr);
		
		$newJson = '
		[
			{
				"id":		"20",
				"title":	"newjson",
				"start":	"2012-02-08 07:30:00",
				"end":		"2012-02-08 11:00:00",
				"editable":	0,
				"allDay":	0,
				"color":	"blue",
				"bgColor":	null,
				"borderColor":null,
				"textColor":null
			}
		]';
		
		//$eventJson = json_encode($eventArr,JSON_NUMERIC_CHECK);
		$eventJson = json_encode($eventArr);
		$this->firephp->log($eventJson);
		//$this->firephp->log($eventArr[0]);
	
		$tmp = $this->json->encode($eventArr);
	
		echo $eventJson;
		//echo $newJson;
		//echo $tmp;
	}
	
	
	

	
	/**
	 * show information about an offer. Called from 'schoolBodyMakeReservation'
	 */
	function getOfferInfo() {
		
		$offerId = $_POST['data']['offerId'];
		
		$options = array(
			'active'	=>'yes',
			'offerId'	=>$offerId
		);
		
		$offerInfo = $this->School_model->getOffer($options);
		$this->firephp->log( $offerInfo, 'offer');
		echo json_encode($offerInfo);
		
		return;
	}
	
	
	
	/**
	 * show information about a schedule. Called from 'schoolBodyMakeReservation'
	 */
	function getScheduleInfo() {
		$this->chromephp->log($_POST);
		$classId = $_POST['data']['classId'];
		
		//$schedules = $this->School_model->getUpcommingSchedule($classId);
		$schedules = $this->School_model->getSchedule(array('class_id'=>$classId));
		
		//echo $tmpMsg;
		echo json_encode($schedules);
		
		return;
	}
	
	/**
	 * Save information about hotel
	 */
	public function setHotelData() {
		
		$okMsg 					= '{"Result":"OK", 		"msg":"Dados alterados"}';
		$errMsg 				= '{"Result":"ERROR", 	"msg":"erro"}';
		$errInvalidValueMsg 	= '{"Result":"ERROR", 	"msg":"Valores inválidos"}';
		$errNotSetMsg 			= '{"Result":"ERROR", 	"msg":"Não foi inserido nenhum valor"}';
		$data 					= '{"var01":"val01","var02":"val02"}';
		
		$user_id = $this->ion_auth->get_user()->id;
		
		$hotel_id = $_POST['hotel_id'];
		
		$this->chromephp->log('POST: ',$_POST);
		
		// only numeric values lower than 100
		$hotelPayment 	= (is_numeric($_POST['hotelPayment']) && ( $_POST['hotelPayment'] < 100 ) ) ? $_POST['hotelPayment'] : null ;
		
		$transportPrice = ( is_numeric($_POST['transportPrice']) ) ? $_POST['transportPrice'] : null ;
		
		if (!$hotelPayment) {
			echo $errInvalidValueMsg;
			return;
		}
		
		if (!$transportPrice) {
			echo $errInvalidValueMsg;
			return;
		}
			
		// update value ... 
		$this->db->where('school_id', $user_id);
		$this->db->where('hotel_id', $hotel_id);
		$succ = $this->db->update('sh',array('hotelPayment'=>$hotelPayment,'transportPrice'=>$transportPrice));
		
		if ($succ) {
			echo $okMsg;
			return;
		}
		else {
			echo $errMsg;
			return;
		}
	}
	
	
	/**
	 * called from profile view to update school data
	 */
	public function setSchoolData() {
		
		$okMsg 					= '{"Result":"OK", 		"msg":"Dados alterados"}';
		$errMsg 				= '{"Result":"ERROR", 	"msg":"erro"}';
		$errNoDataMsg 			= '{"Result":"ERROR", 	"msg":"Sem dados"}';
		$errInvalidValueMsg 	= '{"Result":"ERROR", 	"msg":"Valores inválidos"}';
		$errNotSetMsg 			= '{"Result":"ERROR", 	"msg":"Não foi possivel actualizar os valor"}';
		$data 					= '{"var01":"val01","var02":"val02"}';
		
		//$this->chromephp->log('POST: ', $post);
		
		$user_id = $this->ion_auth->get_user()->id;
		
		$post = NULL;
		
		if (!empty($_POST)) {
			$post = $_POST;
		}
		else {
			echo $errNoDataMsg;
			return;
		}
		
		$data = array(
			'company' 			=> $post['schoolCompany'],
			'phone' 			=> $post['schoolPhone'],
			'address' 			=> $post['schoolAddress']
		);
		
		$this->db->where('user_id', $user_id);
		$succ = $this->db->update('meta', $data);
		
		if ($succ) {
			echo $okMsg;
			return;
		}
		else {
			echo $errNotSetMsg;
			return;
		}
	}	
	
	
	public function tmp() {

		$okMsg 		= '{"Result":"OK"}';
		$errorMsg 	= '{"Result":"ERROR", "Message":"Nao foi possivel associar o extra à oferta" }';
		
		//$this->firephp->log($_POST);
		//$this->chromephp->log('GET: ', $_GET);
		//$this->chromephp->log('POST: ', $_POST);
		
		$now = date('Y-m-d H:i:s',time());
		
		$user_id = $this->ion_auth->get_user()->id;
		$schedule_id = 98;
		$classId = 23;
		$offerId = 5;
		$school_id = 7;
		$hotel_id = 5;
		
		
		
		//$start = '2012-05-01 00:00:00';
		//$end = '2012-05-06 00:00:00';
		//$start = '2012-04-28';
		//$end = '2012-04-28';
		//$start = '1335654000';
		//$end = '1339282800';
		
		//$query = $this->db->get_where('users', array('id'=>3));
		//$query = $this->db->get('users');
		$users = $this->ion_auth->get_active_users('hotel');
		$this->chromephp->log($users);
		//$result = $query->free_result();
		//$this->chromephp->log($query->result());	
		
		echo $okMsg;
		return;
	}
	
	
}

